


/*
消息发送函数

uid:发送者id
fid:接受者id
type:消息类型	
	//normal:普通消息
	shake:抖动消息 （格式shake）
	richface:魔法表情	（格式 richface:表情id）
	
	//url:发送链接
	mix:小图，url，普通消息等混合消息

	pic:发送大图片(格式:pic:临时文件名)

	file:发送文件 (格式: file:临时文件名)


cnt:消息内容
callback:回调函数
*/
//发送总控制器
function sendmsg(uid,fid,receivertype,mode,cnt,callback,filename)
{
	var datatype=null;

	if(mode=="text")
	{
		/*
		输入框内
			较大图片class:ready2send_pic       
			表情	class:ready2send_enmoution
			(链接	class:sulink)需要判断是否链接
		*/
		/*if(isURL(cnt))
		{
			datatype='mix';
		}
		else if(cnt.indexOf('pic:')>=0)
		{
			datatype='pic';
		}
		else if(cnt.indexOf('file:')>=0)
		{
			datatype="file";
		}
		else
		{
			datatype="normal";
		}
		*/
		var strcnt=cnt;

		//清除a标签
		var clear_a=/<a[^>]+href="[^>]+"[^>]*>([^<]+)<\/a>/gmi;
		strcnt=strcnt.replace(clear_a," $1 ");

		//匹配文字中的上的网址
		var reg_link=/(http:\/\/|https:\/\/|ftp:\/\/)?(www\.)?([\w+\.]+)(com|cn|org|net|tw|hk|gov|com\.cn|org\.cn|net\.cn)((\/[^<|^>|^\s|^\"|^\']*)*)/gmi;

		//匹配文字中的图片
		var reg_img=/<img[^>]+format="([^>"]+)"[^>]+name="([^>"]+)"[^>]+>/gmi;

		//var petstr=cnt.match(pet);
		//console.log(petstr);
		//研究的正则暂时无法非&bsp;整词，所以先repalce去除&bsp;再正则匹配替换链接
		//strcnt=strcnt.replace("&nbsp;"," ").replace(reg_link,"[link]$1$2$3$4$5[/link]");
		//strcnt=strcnt.replace(reg_img,"[img format=$1]$2[/img]");
		strcnt=strcnt.replace("&nbsp;"," ").replace(reg_img,"[img format=$1]$2[/img]").replace(reg_link,"[link]$1$2$3$4$5[/link]");
		

		//console.log(cnt);
		//console.log(strcnt);

		var inputbox=$("#inputbox_"+receivertype+fid+"_"+uid+" .inputboxcntpage");
		//判断是否有图片，有则发送
		var imgs=inputbox.find("img");
		//console.log(imgs.length);
		if(imgs.length>0)
		{
			var imgnamearr=[];
			for(var i=0;i<imgs.length;i++)
			{
				imgnamearr.push(imgs.eq(i).attr("name")+"."+imgs.eq(i).attr("format"));
			}
			//console.log(imgnamearr.length);
			if(imgnamearr.length>0)
			{
				imgmulitsend(uid,fid,imgnamearr);
			}
		}
		

		//return;
		sender(uid,fid,receivertype,mode,"text",strcnt,function(msg)
		{
			var msgs={};
			msgs.msg=msg;
			msgs.cnt=strcnt;
			callback(msgs);
		});

	}
	else if(mode=="shake")
	{
		sender(uid,fid,receivertype,mode,"shake",cnt,callback);
	}
	//大图分割上传
	else if(mode=="pic")
	{
		
		imgsend(cnt,uid,fid,receivertype,filename,callback);

	}
	else if(mode=="file")
	{

	}


}
//发送器
function sender(uid,fid,receivertype,mode,datatype,cnt,callback)
{
	var o=
	{
		url:'action/say.php',
		type:'POST',
		data:'u='+uid+'&&to='+fid+'&&cnt='+cnt+'&&rt='+receivertype+'&&dt='+datatype+'&&md='+mode,
		success:callback,
	};
	$.ajax(o);
}

//HTML5图片发送器
 function h5up(data,actionname,callback)
 {
	 //打开xhr2连接
	 var text=null;
	 var xhr=new XMLHttpRequest();
	 xhr.open("POST","action/"+actionname+".php",true);
	 
	 xhr.onreadystatechange=function()
	 {
		 if(this.readyState==4)
		 {
			//text=this.responseText;
			if(typeof callback=='function')
			{
				callback();
			}
		 }
	 }
	 xhr.send(data);
	 //return text;
 }

//检查是否url链接
function isURL (str_url) { 
	var strRegex = '^((https|http|ftp|rtsp|mms)?://)' 
	+ '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' //ftp的user@ 
	+ '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184 
	+ '|' // 允许IP和DOMAIN（域名） 
	+ '([0-9a-z_!~*\'()-]+.)*' // 域名- www. 
	+ '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名 
	+ '[a-z]{2,6})' // first level domain- .com or .museum 
	+ '(:[0-9]{1,4})?' // 端口- :80 
	+ '((/?)|' // a slash isn't required if there is no file name 
	+ '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$'; 
	var re=new RegExp(strRegex); 
	//re.test() 
	if (re.test(str_url)) { 
		return true; 
	} 
	else { 
		return false; 
	} 
} 


function imgsend(fileobj,uid,fid,receivertype,filename,callback)
{
	var upload=null;
		
	var up_apic=function()
	{
		upload=window.setInterval(sendapic,1000);
	};

	//单图片上传方法
	var sendapic=(function()
	{
		
		 const LENGTH=2*1024*1024;//分割大小2m
		 //设置截取长度
		 var start=0;
		 var end=start+LENGTH;
		 //获取文件总长度
		 var fd=null;
		 var newblob=null;
		 var sending=false; 
		return (function()
		{
			//console.log("进来了");
			if(sending==true)
			{
				return;
			}
			var fl=fileobj.files[0];
			 var totalsize=fl.size;
			
			 //截取
			 newblob=fl.slice(start,end);
			 if(newblob==null)
			 {
				 clearInterval(upload);
				 alert("上传文件中断");
				 return;
			 }
			 //将截取好的二进制文件对象加入表单数据
			 fd=new FormData();
			 fd.append("partpic",newblob);
			 
			 fd.append('u',uid);
			 fd.append('to',fid);
			 fd.append('rt',receivertype);
			 fd.append('dt','pic');
			 fd.append('md','pic');
			 fd.append('picname',filename);
			 //up(fd);
			 //console.log(fd);
			// console.log(","+uid+",fid="+fid+","+receivertype+","+filename);
			 h5up(fd,'say');
			
			 //设置截取偏移量
			 start=end;
			 end=start+LENGTH;
			 if(start>=totalsize)
			 {
				 start=0;
				 end=start+LENGTH;
				 fd=null;
				 newblob=null;
				 sending=false; 
				 clearInterval(upload);

				 //加入聊天框
				 /*var date=new Date();
				 var month=date.getMonth()>10?date.getMonth()+1:0+""+parseInt(date.getMonth())+1;
				 var sendtime=date.getFullYear()+"/"+month+"/"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
				 msgcenter.add2box('me',receivertype+fid,uid,'pic',filename,sendtime);
				 */
				 //图片上传完成后添加图片信息到comet中
				 sender(uid,fid,receivertype,'pic','pic',filename,function(msg)
				 {

					callback(msg);

				 });
				 
				 return;
			 }
			 /*var per=100*end/totalsize;
			 if(per>100)
			 {
				 per=100;
			 }
			 $("#bar").html(parseInt(per)+"%");
			 $("#bar").style.width=per+"%";
			 */
			 sending=false;
		}); 
	 })();

	up_apic();
}

function imgmulitsend(uid,fid,name_arr)
{
	for(var i=0;i<name_arr.length;i++)
	{
		var obj=img_ids.get(uid,fid,name_arr[i].split(".")[0]);
		if(obj)
		{
			var fd=new FormData();
			fd.append('md','spic');
			fd.append('img',obj);
			fd.append('fn',name_arr[i]);
			h5up(fd,'say');
		}
	}
}




//公共图片上传方法
function imgsend(uid,fileobj,filename,actionname,callback)
{
	var upload=null;
		
	var up_apic=function()
	{
		upload=window.setInterval(sendapic,1000);
	};

	//单图片上传方法
	var sendapic=(function()
	{
		 const LENGTH=2*1024*1024;//分割大小2m
		 //设置截取长度
		 var start=0;
		 var end=start+LENGTH;
		 //获取文件总长度
		 var fd=null;
		 var newblob=null;
		 var sending=false; 
		return (function()
		{
			//console.log("进来了");
			if(sending==true)
			{
				return;
			}
			var fl=fileobj;
			 var totalsize=fl.size;
			
			 //截取
			 newblob=fl.slice(start,end);
			 if(newblob==null)
			 {
				 clearInterval(upload);
				 alert("上传文件中断");
				 return;
			 }
			 //将截取好的二进制文件对象加入表单数据
			 fd=new FormData();
			 fd.append("partpic",newblob);
			 fd.append('u',uid);
			 fd.append('picname',filename);
			 h5up(fd,actionname);
			
			 //设置截取偏移量
			 start=end;
			 end=start+LENGTH;
			 if(start>=totalsize)
			 {
				 start=0;
				 end=start+LENGTH;
				 fd=null;
				 newblob=null;
				 sending=false; 
				 clearInterval(upload);

				 //加入聊天框
				 /*var date=new Date();
				 var month=date.getMonth()>10?date.getMonth()+1:0+""+parseInt(date.getMonth())+1;
				 var sendtime=date.getFullYear()+"/"+month+"/"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
				 msgcenter.add2box('me',receivertype+fid,uid,'pic',filename,sendtime);
				 */
				 //图片上传完成后添加图片信息到comet中
				 /*sender(uid,fid,receivertype,'pic','pic',filename,function(msg)
				 {

					callback(msg);

				 });
				 */
				 callback(uid,fileobj,filename);
				 
				 return;
			 }
			 /*var per=100*end/totalsize;
			 if(per>100)
			 {
				 per=100;
			 }
			 $("#bar").html(parseInt(per)+"%");
			 $("#bar").style.width=per+"%";
			 */
			 sending=false;
		}); 
	 })();

	up_apic();
}